package com.hxkj.token.utils;


import com.hxkj.token.TokenGenerator;
import com.hxkj.token.enums.TokenExceptionEnum;
import com.hxkj.token.po.Token;
import com.hxkj.token.service.TokenInformationConverter;
import com.platform.common.domain.exception.CustomException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * token工具类
 * <p>
 * Created by chenwei on 2017/11/30.
 */
@Service
public class TokenUtils<T> {

    @Resource
    private TokenGenerator tokenGenerator;

    @Resource
    private TokenInformationConverter<T> tokenInformationConverter;

    /**
     * 获取token
     *
     * @return
     */
    public Token getToken() throws Exception {
        ServletRequestAttributes servletRequestAttributes = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes());
        HttpServletRequest request = servletRequestAttributes.getRequest();
        Map<String, String> headersMap  = getHeadersInfo(request);
        String accessToken = headersMap.get("accesstoken");
        if(StringUtils.isBlank(accessToken)){
            throw new CustomException(TokenExceptionEnum.TOKEN_NOT_EXIST);
        }
        Token token = tokenGenerator.validateToken(accessToken);
        if(token == null){
            throw new CustomException(TokenExceptionEnum.TOKEN_NOT_VALID);
        }
        return token;
    }

    /**
     * get request headers
     * @param request
     * @return
     */
    private Map<String, String> getHeadersInfo(HttpServletRequest request) {
        Map<String, String> map = new HashMap<String, String>();
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = headerNames.nextElement();
            String value = request.getHeader(key);
            map.put(key, value);
        }
        return map;
    }

    /**
     * 获取用户信息
     *
     * @return
     */
    public T getTokenUserInfo() throws Exception {
        Token token  = getToken();
        T  user = tokenInformationConverter.getUserInfoById(token.getUserId());
        return user;
    }


    /**
     * 清除token用户信息
     * @param userId
     * @throws Exception
     */
    public void invalidUserInfo(String userId) throws Exception {
        // 刷新token用户信息
        tokenGenerator.invalidUserInfo(userId);
    }

}
